import React, {
  ReactElement,
  useRef,
  useImperativeHandle,
  forwardRef
} from 'react';
import ViewShot from 'react-native-view-shot';

interface ShotProps {
  style?: any;
  children?: any;
  width: number;
  height: number;
}

const Shot = (
  { style, children, width, height }: ShotProps,
  ref: any
): ReactElement => {
  const shot = useRef<ViewShot>(null);

  const startShot = (): Promise<string> => {
    return new Promise((resolve, reject): void => {
      if (shot && shot.current && shot.current.capture) {
        shot.current.capture().then((uri): void => {
          resolve(uri);
        });
      } else {
        reject();
      }
    });
  };

  useImperativeHandle(ref, (): { [key: string]: any } => {
    return {
      startShot
    };
  });

  return (
    <ViewShot
      ref={shot}
      options={{
        format: 'png',
        quality: 1,
        width,
        height,
        result: 'base64'
      }}
      style={style}
    >
      {children}
    </ViewShot>
  );
};

export default forwardRef(Shot);
